﻿
//
// 版权所有 (c) 2021-2023 JR
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using FluentEmail.Core;
using FluentEmail.Core.Models;
using Microsoft.AspNetCore.SignalR;
using NewLife;
using NewLife.Serialization;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;

namespace EMC.VISITOR.Core.Service;

/// <summary>
/// 系统消息发送服务
/// </summary>
[ApiDescriptionSettings(Order = 370)]
public class SysMessageService : IDynamicApiController, ITransient
{
    private readonly SysCacheService _sysCacheService;
    private readonly EmailOptions _emailOptions;
    private readonly IFluentEmail _fluentEmail;
    private readonly IHubContext<OnlineUserHub, IOnlineUserHub> _chatHubContext;
    public SysMessageService(SysCacheService sysCacheService,
        IOptions<EmailOptions> emailOptions,
        IFluentEmail fluentEmail,
        IHubContext<OnlineUserHub, IOnlineUserHub> chatHubContext)
    {

        _sysCacheService = sysCacheService;
        _emailOptions = emailOptions.Value;
        _fluentEmail = fluentEmail;
        _chatHubContext = chatHubContext;
    }

    /// <summary>
    /// 发送消息给所有人
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("发送消息给所有人")]
    public async Task SendAllUser(MessageInput input)
    {
        await _chatHubContext.Clients.All.ReceiveMessage(input);
    }

    /// <summary>
    /// 发送消息给除了发送人的其他人
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("发送消息给除了发送人的其他人")]
    public async Task SendOtherUser(MessageInput input)
    {
        var user = _sysCacheService.Get<SysOnlineUser>(CacheConst.KeyUserOnline + input.UserId);
        if (user != null)
        {
            await _chatHubContext.Clients.AllExcept(user.ConnectionId).ReceiveMessage(input);
        }
    }

    /// <summary>
    /// 发送消息给某个人
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("发送消息给某个人")]
    public async Task SendUser(MessageInput input)
    {
        var user = _sysCacheService.Get<SysOnlineUser>(CacheConst.KeyUserOnline + input.UserId);
        if (user == null) return;
        await _chatHubContext.Clients.Client(user.ConnectionId).ReceiveMessage(input);
    }

    /// <summary>
    /// 发送消息给某些人
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("发送消息给某些人")]
    public async Task SendUsers(MessageInput input)
    {
        var userlist = new List<string>();
        foreach (var userid in input.UserIds)
        {
            var user = _sysCacheService.Get<SysOnlineUser>(CacheConst.KeyUserOnline + userid);
            if (user != null) userlist.Add(user.ConnectionId);
        }
        await _chatHubContext.Clients.Clients(userlist).ReceiveMessage(input);
    }

    /// <summary>
    /// 发送邮件 -  FluentEmail.Core 发送邮件
    /// </summary>
    /// <param name="message"></param>
    /// <param name="title"></param>
    /// <param name="isHtml"></param>
    /// <returns></returns>
    [DisplayName("发送邮件")]
    public async Task SendEmail([Required] string message, string title = "系统邮件", bool isHtml = false)
    {
        _fluentEmail.Data.ToAddresses = new List<FluentEmail.Core.Models.Address>();
        await _fluentEmail.To(_emailOptions.DefaultToEmail).Subject(title).Body(message, isHtml).SendAsync();
    }

    /// <summary>
    /// 发送邮件 -  FluentEmail.Core 发送邮件
    /// </summary>
    /// <param name="message"></param>
    /// <param name="toEmail">接收者邮箱</param>
    /// <param name="title"></param>
    /// <param name="isHtml"></param>
    /// <returns></returns>
    [DisplayName("发送邮件")]
    public async Task<SendResponse> SendEmail([Required] string message, string mailAddresses, string title = "系统邮件", bool isHtml = false)
    {
        List<Address> addressList = JSON.Deserialize<List<Address>>(mailAddresses);
        _fluentEmail.Data.ToAddresses = new List<FluentEmail.Core.Models.Address>();
        return await _fluentEmail.To(addressList).Subject(title).Body(message, isHtml).SendAsync();
    }

    [DisplayName("发送邮件")]
    public SendResponse SendEmailTwo([Required] string message, string mailAddresses, string title = "系统邮件", bool isHtml = false)
    {
        List<Address> addressList = JSON.Deserialize<List<Address>>(mailAddresses);
        _fluentEmail.Data.ToAddresses = new List<FluentEmail.Core.Models.Address>();
        return  _fluentEmail.To(addressList).Subject(title).Body(message, isHtml).Send();
    }
    /// <summary>
    /// 发送带附件的邮件 -  FluentEmail.Core 发送邮件
    /// </summary>
    /// <param name="message"></param>
    /// <param name="title"></param>
    /// <param name="isHtml"></param>
    /// <param name="attachments">附件</param>
    /// <returns></returns>
    [NonAction]
    public async Task SendEmailContainsAttachments(string message, List<Attachment> attachments, string title = "系统邮件", bool isHtml = false)
    {
        _fluentEmail.Data.ToAddresses = new List<FluentEmail.Core.Models.Address>();
        await _fluentEmail.To(_emailOptions.DefaultToEmail)
             .Subject(title)
             .Body(message, isHtml)
             .Attach(attachments).SendAsync();

        //using Stream stream = new MemoryStream(res); // res：byte[] 转 Stream
        ////   new FluentEmail.Core.Models.Attachment{
        ////   IsInline=true,
        ////   Data=stream,
        ////   ContentId=Guid.NewGuid().ToString(),
        ////   Filename ="派工单信息",
        ////   ContentType = "application/octet-stream"
        ////   }
    }

}

public class WchatReulst
{
    public string errcode { get; set; }
    public string errmsg { get; set; }
    public bool success
    {
        get
        {
            if ((!errcode.IsNullOrEmpty() && errcode == "0")||(!errmsg.IsNullOrEmpty()&& errmsg =="ok"))
                return true;
            return false;
        }
    }
    public string message { get; set; }
}